<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Redis;
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * Copyright (C), 2021-2021, Shall Buy Life info. Co., Ltd.
 * FileName: ${FILE_NAME}
 * Description: 说明
 *
 * @author lwl
 * @Create Date    2021/11/8 11:04
 * @Update Date    2021/11/8 11:04 By lwl
 * @version v1.0
 */
class RabbitmqService
{

    protected static $config = [];

    public function __construct()
    {
        self::$config = config('rabbitmq');
    }

    /**
     * FunctionName：publish
     * Description：生产者发布
     * Author：lwl
     */
    public function publish()
    {
        try {
//            $host = self::$config['host'];
//            //$port = self::$config['port'];
//            $user = self::$config['user'];
//            $password = self::$config['password'];
            $queue = self::$config['queue'];      // 队列名称
            $exchange = self::$config['exchange'];// 交换机名称
            //$key = self::$config['key'];          // 队列绑定交换机时配置的routingKey
            $connection = new AMQPConnection(self::$config['host'], self::$config['port'], self::$config['user'], self::$config['password']);
            $channel = $connection->channel();
//            dd($channel);
            /**
             * 如果管理后台上已经配置了交换机、队列，以及绑定了关系，则不需要下面的3条语句
             */
            $channel->exchange_declare(self::$config['exchange'], 'direct', false, true, false);    // 初始化交换机
            $channel->queue_declare($queue, false, true, false, false);             // 初始化队列
            $channel->queue_bind($queue, $exchange, self::$config['key']);  // 将队列与某个交换机进行绑定，并使用路由关键字
            $msg = '[' . date('Y-m-d H:i:s') . '] ';
            $data = new AMQPMessage($msg, ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
            $channel->basic_publish($data, $exchange, $queue);
            echo "[X] Sent: $msg \n";
            $channel->close();
            $connection->close();
        } catch (\Exception $e) {
            echo $e->getMessage();
        }

    }

    /**
     * FunctionName：subScribe
     * Description：消费者订阅
     * Author：lwl
     */
    public function subScribe()
    {
        $queue = self::$config['queue'];
        $connection = new AMQPConnection(self::$config['host'], self::$config['port'], self::$config['user'], self::$config['password']);
        $channel = $connection->channel();
        $channel->queue_declare($queue, false, true, false, false);
        echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

        $callback = function ($msg) {
            //var_dump($msg);
            echo ' [x] Received ', $msg->body, "\n";
        };

        $channel->basic_consume($queue, '', false, true, false, false, $callback);

        while (count($channel->callbacks)) {
            $channel->wait();
        }
        $channel->close();
        $connection->close();
    }
}
